<template>
    <div class="flex flex-column">
        <div class="hm-select-area hm-padding align-center bg-white font-14">
        <span style="margin-left: 20px">车牌号</span>
        <el-input v-model="searchObj.car_number" placeholder="请输入车牌号" class="hm-select"></el-input>
        <!-- <el-select
            v-model="searchObj.parking_lot_id"
            placeholder="请选择"
            class="hm-select"
        >
            <el-option value="ALL" label="全部"></el-option>
            <el-option
            v-for="item in options"
            :key="item.parking_lot_id"
            :label="item.parking_lot_name"
            :value="item.parking_lot_id"
            >
            </el-option>
        </el-select> -->
        <!-- <span style="margin-left: 20px">车位状态</span>
        <el-select
            v-model="searchObj.is_binding_place"
            placeholder="请选择"
            class="hm-select"
            clearable
        >
            <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            >
            </el-option>
        </el-select> -->
        <!-- <span>时间</span> -->
        <!-- <el-date-picker
            class="hm-date"
            v-model="dateRangeTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        >
        </el-date-picker> -->
        <el-button type="primary" @click="getCarList">搜索</el-button>
        <el-button type="primary" @click="reset">重置</el-button>
        <!-- <el-button
            type="primary"
            plain
            @click="dialogVisibleInsertCar = true"
            style="float: right; margin-left: 70px"
            >添加车辆</el-button
        > -->
        </div>
        <div class="home-table-area bg-white flex-sub">
        <el-row>
            <!-- <el-col :span="12">
            <div class="flex">
                <el-input
                    class="hta-input"
                    placeholder="搜索姓名等关键字"
                    v-model="searchObj.keywords"
                    clearable
                >
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
                <el-button type="primary" >搜索</el-button>
            </div>
            </el-col> -->
            <el-col :span="24">
            <!-- <el-button
                class="marginright"
                style="float: right; color: #f56c6c; border: 0px"
                @click="openHeiming"
                >黑名单</el-button
            > -->
            </el-col>
        </el-row>
        <el-table
            class="home-table"
            ref="tableRef"
            max-height="550"
            :data="tableData"
            v-loading="tableLoading"
            border
            stripe
            :header-cell-style="{
                background: '#F7F7F7',
                color: '#101010',
                fontWeight: 'normal',
            }"
        >
            <el-table-column type="index" width="60" label="序号" />
            <el-table-column
            prop="car_number"
            label="车牌号"
            header-align="center"
            align="center"
            ></el-table-column>
            <el-table-column
            label="类型"
            v-slot="{row}"
            header-align="center"
            align="center"
            >
            {{row.car_type === 'GREEN' ? '绿牌' : row.car_type === 'BLUE' ? '蓝牌' : '黄牌'}}
            </el-table-column>
            <el-table-column
            prop="driver"
            label="车主"
            header-align="center"
            align="center"
            ></el-table-column>
            <el-table-column
            prop="driver_phone"
            label="联系电话"
            header-align="center"
            align="center"
            width="200"
            ></el-table-column>
            <!-- <el-table-column
            prop="parking_name"
            label="停车场"
            header-align="center"
            align="center"
            >
            </el-table-column> -->
            <!-- <el-table-column label="车位状态" header-align="center" align="center">
            <template slot-scope="scope">
                <span class="bdcolor">{{scope.row.parking_place_id ? '已绑定' : '未绑定'}}</span>
                <div v-if="scope.row.partition_id">
                <span >已绑定</span>
                </div>
                <div v-if="scope.row.partition_id === 'NO'">
                <span class="bdnocolor">未绑定</span>
                </div>
                {{ scope.row.status === 'IN' ? '已绑定' : scope.row.status === 'OUT' ? '未绑定' : '未绑定' }}
            </template>
            </el-table-column> -->
            <!-- <el-table-column
            label="起始时间"
            header-align="center"
            align="center"
            width="280"
            >
            <template slot-scope="scope">
                {{new Date(scope.row.startTime).toLocaleString().split(' ')[0] +' ~ '+ new Date(scope.row.endTime).toLocaleString().split(' ')[0]}}
            </template>
            </el-table-column> -->
            <el-table-column 
                header-align="center" 
                align="center" 
                v-slot="{row}"
                label="操作">
                <el-button type="text" @click="showEdit(row)">编辑</el-button>
                <!-- <el-button type="text" @click="delCar(row)">删除</el-button> -->
                <el-button type="text" style="color:red" @click="heimingdan(row)" >{{row.status ? '加入黑名单' : '解除黑名单'}}</el-button>
            </el-table-column>
        </el-table>
        <!-- <el-pagination
            class="hm-page"
            background
            :page-size="searchObj.page_num"
            layout="prev, pager, next"
            :total="total"
            @current-change="sizeChange"
        >
        </el-pagination> -->
        </div>
        <!--添加车辆弹框-->
        <el-dialog
            class="font-col"
            :title="titles"
            :visible.sync="dialogVisibleInsertCar"
            width="45%"
            :before-close="handleClose"
        >
        <el-form 
            :model="addForm" 
            ref="addForm" 
            :rules="rules"
            label-width="120px" >
            <el-row>
            <el-form-item label="车牌号种类" prop="car_type">
                <el-radio-group v-model="addForm.car_type" @change="platemodel">
                <el-radio label="BLUE">蓝牌</el-radio>
                <el-radio label="YELLOW">黄牌</el-radio>
                <el-radio label="GREEN">绿牌</el-radio>
                <el-radio label="OTHER">其他</el-radio>
                </el-radio-group>
            </el-form-item>
            </el-row>
            <el-row>
            <el-form-item label="车牌号" prop="car_number">
                <el-input 
                    v-model="addForm.car_number" 
                    :maxlength="addForm.car_type === 'GREEN' ? 8 : 7"
                    :minlength="addForm.car_type === 'GREEN' ? 8 : 7"
                    :disabled="!addForm.car_type"
                    placeholder=""></el-input>
                <!-- <el-col :span="2" class="mright">
                <el-input
                    maxlength="1"
                    v-model="carnumber.firstnumber"
                    @input="moveNext(carnumber.firstnumber, 5)"
                ></el-input>
                </el-col>
                <el-col :span="2" class="marginright">
                <el-input
                    maxlength="1"
                    v-model="carnumber.secondnumber"
                    @input="moveNext(carnumber.secondnumber, 6)"
                ></el-input>
                </el-col>
                <el-col :span="2" class="mright">
                <el-input
                    maxlength="1"
                    v-model="carnumber.thirdnumber"
                    @input="moveNext(carnumber.thirdnumber, 7)"
                ></el-input>
                </el-col>
                <el-col :span="2" class="mright">
                <el-input
                    maxlength="1"
                    v-model="carnumber.fourthnumber"
                    @input="moveNext(carnumber.fourthnumber, 8)"
                ></el-input>
                </el-col>
                <el-col :span="2" class="mright">
                <el-input
                    maxlength="1"
                    v-model="carnumber.fifthnumber"
                    @input="moveNext(carnumber.fifthnumber, 9)"
                ></el-input>
                </el-col>
                <el-col :span="2" class="mright">
                <el-input
                    maxlength="1"
                    v-model="carnumber.sixthnumber"
                    @input="moveNext(carnumber.sixthnumber, 10)"
                ></el-input>
                </el-col>
                <el-col :span="2" class="mright">
                <el-input
                    maxlength="1"
                    v-model="carnumber.seventhnumber"
                    @input="moveNext(carnumber.seventhnumber, 11)"
                ></el-input>
                </el-col>
                <el-col :span="2" v-if="isGreen">
                <el-input
                    maxlength="1"
                    v-model="carnumber.eighthnumber"
                    @input="moveNext(carnumber.eighthnumber, 12)"
                ></el-input>
                </el-col> -->
            </el-form-item>
            </el-row>
            <el-row>
            <el-col :span="12">
                <el-form-item label="车主姓名" prop="driver">
                <el-input
                    v-model="addForm.driver"
                    placeholder="请输入车主姓名"
                ></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="联系方式" prop="driver_phone">
                <el-input
                    v-model="addForm.driver_phone"
                    placeholder="请输入联系方式"
                ></el-input>
                </el-form-item>
            </el-col>
            </el-row>
            <el-row>
            <!-- <el-form-item label="停车场">
                <el-select
                v-model="addForm.parking_lot_id"
                @change="val => getCar(val)"
                placeholder="请选择停车场"
                >
                <el-option
                    v-for="item in options"
                    :key="item.parking_lot_id"
                    :label="item.parking_lot_name"
                    :value="item.parking_lot_id"
                >
                </el-option>
                </el-select>
            </el-form-item> -->
            </el-row>
            <el-row>
            <!-- <el-form-item label="绑定车位(选填)">
                <el-col :span="11">
                <el-select
                    v-model="addForm.partition_id"
                    @change="val => getWei(val)"
                    :disabled="!addForm.parking_lot_id"
                    placeholder="区"
                >
                    <el-option
                    v-for="item in optionArea"
                    :key="item.area_id"
                    :label="item.name"
                    :value="item.area_id"
                    >
                    </el-option>
                </el-select>
                </el-col>
                <el-col :span="11">
                <el-select 
                    :disabled="!addForm.partition_id"
                    v-model="addForm.parking_place_id" 
                    placeholder="位">
                    <el-option
                    v-for="item in optionParking"
                    :key="item.space_id"
                    :label="item.parking_place_number"
                    :value="item.space_id"
                    >
                    </el-option>
                </el-select>
                </el-col>
            </el-form-item> -->
            </el-row>
            <el-row>
            <!-- <el-form-item label="有效时间">
                <el-date-picker
                    v-model="dateRangeTimes"
                    @change="getTime"
                    type="daterange"
                    format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                >
                </el-date-picker>
            </el-form-item> -->
            </el-row>
        </el-form>
        <div class="margintop marginbottom" style="text-align: center">
            <!-- <el-button
                type="danger"
                v-if="titles === '编辑车辆'"
                plain
            ><span style="margin: 0 20px">加入黑名单</span></el-button
            > -->
            <el-button type="primary" v-if="titles === '编辑车辆'" @click="addCar"
            ><span style="margin: 0 40px">确定</span></el-button
            >
            <el-button
                type="primary"
                v-if="titles === '添加车辆'"
                @click="addCar"
            ><span style="margin: 0 40px">确定</span></el-button
            >
        </div>
        </el-dialog>
        <!--黑名单弹框-->
        <el-dialog
        class="font-col"
        title="黑名单"
        :visible.sync="dialogVisibleBlack"
        width="45%"
        :before-close="handleCloses"
        >
        <el-table
            class="home-table"
            :data="tableBlack"
            border
            stripe
            v-loading="blackLoading"
        >
            <el-table-column
            prop="car_number"
            label="车牌号"
            header-align="center"
            align="center"
            ></el-table-column>
            <el-table-column
            prop="driver"
            label="车主"
            header-align="center"
            align="center"
            ></el-table-column>
            <el-table-column
            prop="driver_phone"
            label="联系电话"
            header-align="center"
            align="center"
            width="200"
            ></el-table-column>
            <el-table-column 
                header-align="center" 
                align="center" 
                v-slot="{row}"
                label="操作">
                <el-button type="text" 
                @click="cancleHeiming(row)"
                >解除</el-button
                >
            </el-table-column>
        </el-table>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: "index",
    data() {
        return {
            dateRangeTime: [],
            dateRangeTimes: [],
            dialogVisibleInsertCar: false,
            dialogVisibleBlack: false,
            isGreen: false,
            searchObj: {
                car_number: ''
            },
            typeOptions: [
                {
                label: "绑定",
                value: "YES",
                },
                {
                label: "未绑定",
                value: "NO",
                },
            ],
            addForm: {},
            carnumber: {
                firstnumber: "",
                secondnumber: "",
                thirdnumber: "",
                fourthnumber: "",
                fifthnumber: "",
                sixthnumber: "",
                seventhnumber: "",
                eighthnumber: "",
            },
            total: 10,
            tableData: [],
            tableBlack: [],
            titles: "添加车辆",
            options: [],
            optionArea: [],
            optionParking: [],
            admin_id: "",
            rules: { 
                car_type: [{ required: true, message: '请选择车牌号种类', trigger: 'change' }],
                driver: [{ required: true, message: '请输入车主姓名', trigger: 'blur' }],
                parking_lot_id: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
                driver_phone: [{ required: true, message: '请选择停车场', trigger: 'change' }],
                car_number: [{ required: true, message: '请输入完整的车牌号', trigger: 'blur' }],
            },
            tableLoading: false,
            blackLoading: false,
            parkingLotList: []
        };
    },
    mounted() {
        // this.admin_id = this.$store.state.adminId
        this.getCarList()
        this.getParkingLotList()
        // this.getHeiming()

        // this.getparkingLotListByLoginId()
        // this.getblacklist()
    },
    methods: {
        platemodel(){
            if(this.addForm.car_type==='GREEN')
                this.isGreen= true
            else{
                this.isGreen= false
            }
        },
        handleClose() { 
            this.addForm = {}
            this.dateRangeTimes = []
            this.titles = '添加车辆'
            this.dialogVisibleInsertCar = false
        },
        handleCloses() { 
            this.dialogVisibleBlack = false
        },
        // 车牌号
        moveNext(val,index){
            if(val.length===1){
                if(this.isGreen){
                if(index!=12)
                    document.forms[0].elements[index].focus()
                }else{
                if(index!=11)
                    document.forms[0].elements[index].focus()
                }  
            } 
            else if(val.length===0){
                if(index!=5)
                document.forms[0].elements[index-2].focus()
            }
        },
        addCar() { 
            this.$refs.addForm.validate(async val => { 
                if(!val) return false
                try{ 
                    const { car_type, endTime, startTime, car_number, partition_id, parking_place_id } = this.addForm
                    // if(this.dateRangeTimes.length === 0) return this.$message.error('请选择有效时间')
                    if(car_type === 'GREEN'){ 
                        if(car_number.length < 8) return this.$message.error('请输入完整的车牌号')
                    }else{
                        if(car_number.length < 7) return this.$message.error('请输入完整的车牌号')
                    }
                    // if(partition_id && !parking_place_id) return  this.$message.error('请选择车位')
                    // if(car_type === 'BLUE' || car_type === 'YELLOW' || car_type === 'OTHER'){ 
                    //     if(!this.carnumber.firstnumber|| !this.carnumber.secondnumber || !this.carnumber.thirdnumber || !this.carnumber.fourthnumber || !this.carnumber.fifthnumber|| !this.carnumber.sixthnumber || !this.carnumber.seventhnumber)
                    //     return this.$message.error('请输入完整的车牌号')
                        
                    // }else{ 
                    //     if(!this.carnumber.firstnumber|| !this.carnumber.secondnumber || !this.carnumber.thirdnumber || !this.carnumber.fourthnumber || !this.carnumber.fifthnumber|| !this.carnumber.sixthnumber || !this.carnumber.seventhnumber || !this.carnumber.eighthnumber)
                    //     return this.$message.error('请输入完整的车牌号')
                    // }

                    // let car_number = this.carnumber.firstnumber+this.carnumber.secondnumber+this.carnumber.thirdnumber+this.carnumber.fourthnumber+this.carnumber.fifthnumber+this.carnumber.sixthnumber+this.carnumber.seventhnumber+this.carnumber.eighthnumber
                    // for(let val of this.options){ 
                    //     if(this.addForm.parking_lot_id === val.parking_lot_id){ 
                    //         this.$set(this.addForm,'parking_name',val.parking_lot_name)
                    //     }
                    // }
                    console.log(this.addForm);
                    // let method = this.titles === '编辑车辆' ? 'updateUserCar' : 'addCar'
                    const { data : res } = await this.$api.Car.updateUserCar({ 
                        ...this.addForm,
                        // car_number,
                        // endTime: this.dateRangeTimes.length > 0 ? this.dateRangeTimes[1].toLocaleString() : '',
                        // startTime: this.dateRangeTimes.length > 0 ? this.dateRangeTimes[0].toLocaleString() : ''
                    })
                    if(res.code) return this.$message.error(res.msg)
                    this.$message.success(res.msg)
                    this.dialogVisibleInsertCar = false 
                    this.getCarList()
                }catch(e) { 
                    console.log(e);
                }
            })
        },
        async getCarList() { 
            try{ 
                this.tableLoading = true
                const { data : res } = await this.$api.Car.getAllCarList({
                    ...this.searchObj
                })
                if(res.code) return this.$message.error(res.msg)
                this.tableData = res.result
            }catch(e) { 
                console.log(e);
            }finally{ 
                this.tableLoading = false
            }
        },
        reset() { 
            this.searchObj = { 
                car_number :''
            }
            this.getCarList()
        },
        async getParkingLotList(){
            try{ 
                const { data : res } = await this.$api.Parking.getParkingList({})
                if(res.code) return this.$message.error(res.msg)
                this.options = this._.cloneDeep(res.result)
            }catch(e){ 
                console.log(e);
            }
        },
        showEdit(data) { 
            this.dialogVisibleInsertCar = true
            this.titles = '编辑车辆'
            this.addForm = this._.cloneDeep(data)
            // let arr =  []
            // this.getCar(data.parking_lot_id)
            // if(data.partition_id) { 
            //     this.getWei(data.partition_id)
            // }
            // console.log(obj);
            // arr.push(obj.startTime.toLocaleString(),obj.endTime.toLocaleString())
            // this.$set(this,'dateRangeTimes',arr)
            // this.$set(obj,'startTime',new Date(obj.startTime).toLocaleString())
            // this.$set(obj,'endTime',new Date(obj.endTime).toLocaleString())
            // this.dateRangeTimes[0] = 
            // this.dateRangeTimes[1] = 
            // let obj1 = {}
            // let num = this._.cloneDeep(this.carnumber)
            // for(let i in num){
            //     for(let val of obj?.car_number?.split('')){ 
            //         obj1[i] = val
            //     }
            // }
            // this.carnumber = this._.cloneDeep(obj1)
            // this.addForm = this._.cloneDeep(obj)
        },
        getTime(val){ 
            this.$set(this.addForm,'startTime',val[0].toLocaleString())
            this.$set(this.addForm,'endTime',val[1].toLocaleString())
        },
        delCar(data){ 
            this.$confirm('此操作将删除该车辆,是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try{ 
                    const { data : res } = await this.$api.Car.delUserCar({ 
                        car_id: data.car_id
                    })
                    if(res.code) return this.$message.error(res.msg)
                    this.$message.success('删除成功!')
                    this.getCarList()
                }catch(e) {
                    console.log(e);
                }
            }).catch(() => {
                this.$message({
                type: 'info',
                message: '已取消删除'
                });
            });
        },
        dateFormat(time) {
            let date = new Date(time);
            let str = date.toISOString().replace('T',' ');
            console.log();
            // return str.substr(0, str.lastIndexOf('.'));
            return str?.split(' ')[0]
        },
        heimingdan(val) { 
            let msg = val.status ? '此操作将车辆添加至黑名单,是否继续' : '此操作将车辆接触黑名单,是否继续'
            this.$confirm(msg, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try{ 
                    const { car_id } = val
                    // this.dateFormat(startTime)
                    // this.dateFormat(endTime)
                    const { data : res } = await this.$api.Car.addCarBlack({ 
                        car_id,
                        status: val.status ? 0 : 1
                    })
                    if(res.code) return this.$message.error(res.msg)
                    let msg1 = val.status ? '拉黑成功' : '接触黑名单成功'
                    this.$message.success(msg1)
                    console.log(res);
                    // const { data1 : res1 } = await this.$api.Car.delCar({ 
                    //     car_id: val.car_id
                    // })
                    // console.log(res1);
                    // this.$message.success('添加黑名单成功!')
                    this.getCarList()
                    // this.getHeiming()
                }catch(e) { 
                    console.log(e);
                }
            }).catch(() => {
                this.$message({
                type: 'info',
                message: val.status ? '已取消添加至黑名单' : '已取消接触黑名单'
                });
            });
        },
        openHeiming() { 
            this.dialogVisibleBlack = true
        },
        // async getHeiming() { 
        //     try{ 
        //         this.blackLoading = true
        //         const { data : res } = await this.$api.Car.getBlack({})
        //         if(res.code) return this.$message.error(res.msg)
        //         this.tableBlack = res.result
        //     }catch(e) { 
        //         console.log(e);
        //     }finally{ 
        //         this.blackLoading = false
        //     }
        // },
        cancleHeiming(val) { 
            console.log(val);
            this.$confirm('此操作将该车辆解除黑名单,是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try{ 
                    const { data : res } = await this.$api.Car.delBlack({ 
                        car_id: val.car_id
                    })
                    if(res.code) return this.$message.error(res.msg)
                    const { endTime, startTime } = val
                    const { data1 : res1 } = await this.$api.Car.addCar({ 
                        ...val,
                        endTime: endTime ? this.dateFormat(endTime) : '',
                        startTime: startTime ?  this.dateFormat(startTime): ''
                    })
                    console.log(res1);
                    this.$message.success('解除成功!')
                    // this.getHeiming()
                    this.getCarList()
                }catch(e) {
                    console.log(e);
                }
            }).catch(() => {
                this.$message({
                type: 'info',
                message: '已取消解除'
                });
            });
        },
        async getCar(id){ 
            try{ 
                this.$set(this.addForm,'partition_id','')
                this.$set(this.addForm,'parking_place_id','')
                const { data : res } = await this.$api.Parking.getAreaList({ 
                    parking_lot_id: id
                })
                if(res.code) return this.$message.error(res.msg)
                this.optionArea = res.result
            }catch(e){ 
                console.log(e);
            }
        },
        async getWei(id){ 
            try{ 
                this.$set(this.addForm,'parking_place_id','')
                const { data : res } = await this.$api.Parking.getSpaceList({ 
                    area_id: id
                })
                if(res.code) return this.$message.error(res.msg)
                this.optionParking = res.result
            }catch(e){ 
                console.log(e);
            }
        },
    },
};
</script>

<style scoped>
.hta-input {
  width: 260px;
  margin-right: 23px;
}
.hm-date {
  margin: 0 15px;
  /*width: 136px;*/
}
/*  弹框*/
.font-col {
  color: #101010;
}
.bdcolor {
  padding: 8px 15px;
  border-radius: 47%;
  color: #ffff;
  background-color: rgb(74, 235, 181);
}
.bdnocolor {
  padding: 8px 15px;
  border-radius: 47%;
  color: #ffff;
  background-color: rgb(209, 207, 207);
}
.mright {
  margin-right: 5px;
}
.flex{
    display: flex;
    width: 100%;
    justify-content: space-between;
}
</style>
